<template>
	<image :src="svgData" :style="{width: width, height:height}"></image>
</template>

<script>
	const fs = wx.getFileSystemManager()
	import CryptoJS from 'crypto-js'
	// import {
	// 	Base64
	// } from './base64.js'
	// const base64 = new Base64()

	export default {
		props: {
			src: {
				type: String,
				require: true
			},
			color: {
				type: String
			},
			width: {
				type: String,
				require: true
			},
			height: {
				type: String,
				require: true
			}
		},
		data() {
			return {
				svgData: ''
			}
		},
		created() {
			this.getSvgFile(this.src, this.color)
		},
		methods: {
			getSvgFile(src, color) {
				let _this = this;
				fs.readFile({
					filePath: src,
					encoding: 'utf-8',
					position: 0,
					success(res) {
						let sourceFile = res.data;
						let newFile = _this.changeColor(sourceFile, color);
						let svgBase64File = CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(
							newFile));
						_this.svgData = 'data:image/svg+xml;base64,' + svgBase64File
					},
					fail(res) {
						console.error(res)
					}
				})
			},
			changeColor(sourceFile, color) {
				let newSvg;
				if (/fill=".*?"/.test(sourceFile)) {
					newSvg = sourceFile.replace(/fill=".*?"/g, `fill="${color}"`); // SVG有默认色
				} else {
					newSvg = sourceFile.replace(/<svg /g, `<svg fill="${color}" `); // 无默认色
				}
				return newSvg
			}
		}
	}
</script>

<style lang="scss" scoped>
</style>